﻿using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using Utils;

namespace Test105
{
    internal class Program
    {
        static int num = 0;
        static ConcurrentDictionary<int, object> dict = new ConcurrentDictionary<int, object>();

        static void Main(string[] args)
        {
            // 设置一下线程池数量可以大大提升批量请求速度
             ThreadPool.SetMinThreads(650, 650);
             ThreadPool.SetMinThreads(600, 600); 

            CalcSpeed();

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    // 批量请求，第1个参数是一个集合，第2个参数是最大并行度
                    Parallel.ForEach(Enumerable.Range(0, 500), new ParallelOptions() { MaxDegreeOfParallelism = 500 }, (i, c) =>
                    {
                        Request(i);
                    });

                    Thread.Sleep(1);
                }
            }, TaskCreationOptions.LongRunning);

            Console.WriteLine($"Main函数结束");
            Console.ReadLine();
        }

        static void Request(int index)
        {
            dict.TryAdd(index, null);

            string url = "http://localhost:5028/Test/TestGet";
            string result = HttpUtil.HttpGet(url);
            Interlocked.Increment(ref num);
        }

        static void CalcSpeed()
        {
            _ = Task.Factory.StartNew(() =>
            {
                Stopwatch sw = Stopwatch.StartNew();
                while (true)
                {
                    Thread.Sleep(2000);
                    double speed = num / sw.Elapsed.TotalSeconds;
                    ThreadPool.GetMaxThreads(out int w1, out int c1);
                    ThreadPool.GetAvailableThreads(out int w2, out int c2);
                    Console.WriteLine($"有 1 个 while(true) 在执行，线程池活动线程数：{(w1 - w2).ToString().PadRight(3)}  速度：{speed:#### ####.0} 次/秒");
                }
            }, TaskCreationOptions.LongRunning);
        }
    }
}
